<template>
  <div class="order-manager">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>订单管理</h2>
      <el-tag type="info">共 {{ total }} 个订单</el-tag>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="operation-area" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.id" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="(label, value) in orderStatusMap" :key="value" :label="label" :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 管理员可以查看所有用户订单 -->
        <el-form-item label="用户名称" v-if="isAdmin">
          <el-input v-model="searchForm.username" placeholder="请输入用户名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" plain type="primary" @click="handleSearch">查询</el-button>
          <el-button size="medium" plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-time"></i></div>
                <div class="stat-title">待付款</div>
              </div>
              <div class="stat-value">{{ statistics.pendingPaymentCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-box"></i></div>
                <div class="stat-title">待发货</div>
              </div>
              <div class="stat-value">{{ statistics.paidCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-truck"></i></div>
                <div class="stat-title">已发货</div>
              </div>
              <div class="stat-value">{{ statistics.shippedCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-circle-check"></i></div>
                <div class="stat-title">已完成</div>
              </div>
              <div class="stat-value">{{ statistics.completedCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 添加待处理退款统计卡片 -->
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card refund-stat-card" v-if="isMerchant">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon refund-icon"><i class="el-icon-refresh-left"></i></div>
                <div class="stat-title">待处理退款</div>
              </div>
              <div class="stat-value refund-value">{{ statistics.pendingRefundCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-s-order"></i></div>
                <div class="stat-title">订单总数</div>
              </div>
              <div class="stat-value">{{ statistics.totalCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-money"></i></div>
                <div class="stat-title">今日销售额</div>
              </div>
              <div class="stat-value">¥{{ statistics.todayAmount ? Number(statistics.todayAmount).toFixed(2) : '0.00' }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-wallet"></i></div>
                <div class="stat-title">本月销售额</div>
              </div>
              <div class="stat-value">¥{{ statistics.monthAmount ? Number(statistics.monthAmount).toFixed(2) : '0.00' }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table 
        :data="orders" 
        border 
        style="width: 100%" 
        :default-sort="{prop: 'createdAt', order: 'descending'}"
        :row-class-name="getRowClassName">
        <el-table-column prop="id" label="订单ID" width="120" sortable></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column label="用户信息" width="150">
          <template slot-scope="scope">
            <div class="user-info">
              <div class="user-name">{{ scope.row.user?.name || '未知用户' }}</div>
              <div class="user-username text-muted">{{ scope.row.user?.username }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="300">
          <template slot-scope="scope">
            <div class="product-info">
              <el-image :src="'api'+scope.row.product.imageUrl" :preview-src-list="['api'+scope.row.product.imageUrl]" fit="cover"
                style="width: 50px; height: 50px">
              </el-image>
              <div class="product-detail">
                <div class="product-name">{{ scope.row.product.name }}</div>
                <div class="product-price">
                  ¥{{ scope.row.price.toFixed(2) }} × {{ scope.row.quantity }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="订单金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="收货信息" width="200">
          <template slot-scope="scope">
            <div>{{ scope.row.recvAddress }}</div>
            <div>{{ scope.row.recvPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template slot-scope="scope">
            <div class="status-wrapper">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ orderStatusMap[scope.row.status] }}
              </el-tag>
              <!-- 添加退款标记 -->
              <el-tag 
                v-if="orderRefundStatus[scope.row.id] && orderRefundStatus[scope.row.id].status === 0"
                type="danger"
                size="mini"
                class="refund-badge">
                待退款
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="下单时间" width="180" :sortable="true">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <!-- 根据订单状态和用户角色显示不同的操作按钮 -->
            <template v-if="isMerchant">
              <!-- 商户只能发货 -->
              <el-button 
                v-if="scope.row.status === 1" 
                type="text" 
                size="small" 
                @click="handleShip(scope.row)">发货</el-button>
              <!-- 添加查看物流按钮 -->
              <el-button 
                v-if="scope.row.status >= 2 " 
                type="text" 
                size="small" 
                @click="handleViewLogistics(scope.row)">查看物流</el-button>
              <!-- 修改退款按钮显示逻辑 -->
              <el-button 
                v-if="orderRefundStatus[scope.row.id] && orderRefundStatus[scope.row.id].status === 0" 
                type="danger" 
                size="small" 
                class="refund-action-btn"
                @click="handleRefund(scope.row)">处理退款</el-button>
              <el-button 
                v-if="orderRefundStatus[scope.row.id] && orderRefundStatus[scope.row.id].status !== 0" 
                type="text" 
                size="small" 
                @click="handleDetail(scope.row)">查看退款</el-button>
            </template>
            
            <template v-else-if="isAdmin">
              <!-- 管理员只能删除订单 -->
              <el-button 
                type="text" 
                size="small" 
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
            
            <el-button type="text" size="small" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.size" @pagination="getList" />
    </el-card>

    <!-- 添加退款处理对话框 -->
    <el-dialog title="退款处理" :visible.sync="refundDialogVisible" width="600px">
      <div v-if="refundInfo" class="refund-info">
        <div class="refund-header">
          <div class="refund-status">
            <el-tag :type="getRefundStatusType(refundInfo.status)">
              {{ refundStatusMap[refundInfo.status] }}
            </el-tag>
          </div>
          <div class="refund-no">
            <span class="label">退款单号：</span>
            <span>{{ refundInfo.refundNo }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>退款信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ refundInfo.orderNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">退款金额：</span>
            <span class="value highlight">¥{{ refundInfo.refundAmount }}</span>
          </div>
          <div class="detail-item">
            <span class="label">退款原因：</span>
            <span class="value">{{ refundInfo.refundReason }}</span>
          </div>
          <div class="detail-item">
            <span class="label">申请时间：</span>
            <span class="value">{{ formatTime(refundInfo.applyTime) }}</span>
          </div>
        </div>
        
        <div class="detail-section" v-if="refundInfo.evidenceImages">
          <h4>凭证图片</h4>
          <div class="evidence-images">
            <el-image 
              v-for="(img, index) in parseEvidenceImages(refundInfo.evidenceImages)" 
              :key="index"
              :src="img"
              fit="cover"
              style="width: 100px; height: 100px; margin-right: 10px; border-radius: 4px;"
              :preview-src-list="parseEvidenceImages(refundInfo.evidenceImages)">
            </el-image>
          </div>
        </div>
      </div>
      <div class="refund-operation">
        <el-form :model="refundForm" label-width="80px">
          <el-form-item label="处理结果">
            <el-radio-group v-model="refundForm.status">
              <el-radio :label="1">同意退款</el-radio>
              <el-radio :label="2">拒绝退款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="处理备注">
            <el-input type="textarea" v-model="refundForm.remark" :rows="3" placeholder="请输入处理备注（可选）"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRefund">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="600px">
      <div class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单编号：</span>
            <span>{{ currentOrder?.id }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ currentOrder?.orderNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatTime(currentOrder?.createdAt) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getOrderStatusType(currentOrder?.status)">
              {{ orderStatusMap[currentOrder?.status] }}
            </el-tag>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="detail-section">
          <h4>商品信息</h4>
          <div class="product-detail-info">
            <el-image 
              :src="'api'+currentOrder?.product?.imageUrl" 
              :preview-src-list="['api'+currentOrder?.product?.imageUrl]"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 4px;">
            </el-image>
            <div class="product-info-right">
              <div class="product-name">{{ currentOrder?.product?.name }}</div>
              <div class="product-price">
                <span>单价：¥{{ currentOrder?.price }}</span>
                <span class="quantity">数量：{{ currentOrder?.quantity }}</span>
              </div>
              <div class="total-price">
                总价：¥{{ currentOrder?.totalPrice }}
              </div>
            </div>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="detail-section">
          <h4>收货信息</h4>
          <div class="detail-item">
            <span class="label">收货人：</span>
            <span>{{ currentOrder?.recvName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ currentOrder?.recvPhone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">收货地址：</span>
            <span>{{ currentOrder?.recvAddress }}</span>
          </div>
        </div>

        <!-- 添加商户信息部分 -->
        <div class="detail-section">
          <h4>商户信息</h4>
          <div class="detail-item">
            <span class="label">商户姓名：</span>
            <span>{{ currentOrder?.merchant?.name }}</span>
          </div>
        </div>

        <!-- 退款信息(如果有) -->
        <div class="detail-section" v-if="orderRefund">
          <h4>退款信息</h4>
          <div class="detail-item">
            <span class="label">退款单号：</span>
            <span>{{ orderRefund.refundNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">退款状态：</span>
            <el-tag :type="getRefundStatusType(orderRefund.status)">
              {{ refundStatusMap[orderRefund.status] }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">退款原因：</span>
            <span>{{ orderRefund.refundReason }}</span>
          </div>
          <div class="detail-item">
            <span class="label">退款金额：</span>
            <span class="value highlight">¥{{ orderRefund.refundAmount }}</span>
          </div>
          <div class="detail-item" v-if="orderRefund.applyTime">
            <span class="label">申请时间：</span>
            <span>{{ formatTime(orderRefund.applyTime) }}</span>
          </div>
          <div class="detail-item" v-if="orderRefund.processTime">
            <span class="label">处理时间：</span>
            <span>{{ formatTime(orderRefund.processTime) }}</span>
          </div>
          <div class="detail-item" v-if="orderRefund.successTime">
            <span class="label">退款时间：</span>
            <span>{{ formatTime(orderRefund.successTime) }}</span>
          </div>
          <div class="detail-item" v-if="orderRefund.merchantRemark">
            <span class="label">处理备注：</span>
            <span>{{ orderRefund.merchantRemark }}</span>
          </div>
          
          <!-- 添加凭证图片显示 -->
          <div v-if="orderRefund.evidenceImages" class="evidence-section">
            <h5>凭证图片</h5>
            <div class="evidence-images">
              <el-image 
                v-for="(img, index) in parseEvidenceImages(orderRefund.evidenceImages)" 
                :key="index"
                :src="img"
                fit="cover"
                style="width: 80px; height: 80px; margin-right: 8px; border-radius: 4px;"
                :preview-src-list="parseEvidenceImages(orderRefund.evidenceImages)">
              </el-image>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 修改发货对话框 -->
    <el-dialog title="发货处理" :visible.sync="shipDialogVisible" width="500px">
      <el-form :model="shipForm" :rules="shipRules" ref="shipForm" label-width="100px">
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="shipForm.receiverName" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="receiverPhone">
          <el-input v-model="shipForm.receiverPhone" disabled></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="receiverAddress">
          <el-input type="textarea" v-model="shipForm.receiverAddress" disabled :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="预计到达" prop="expectedArrivalTime">
          <el-date-picker
            v-model="shipForm.expectedArrivalTime"
            type="datetime"
            placeholder="选择预计到达时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="快递公司" prop="companyName">
          <el-select v-model="shipForm.companyName" placeholder="请选择快递公司">
            <el-option label="顺丰快递" value="顺丰快递"></el-option>
            <el-option label="中通快递" value="中通快递"></el-option>
            <el-option label="圆通快递" value="圆通快递"></el-option>
            <el-option label="韵达快递" value="韵达快递"></el-option>
            <el-option label="申通快递" value="申通快递"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNumber">
          <el-input v-model="shipForm.trackingNumber" placeholder="请输入快递单号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitShip">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加物流信息对话框 -->
    <el-dialog title="物流信息" :visible.sync="logisticsDialogVisible" width="600px">
      <div class="logistics-info" v-if="logisticsInfo">
        <div class="logistics-header">
          <div class="company-info">
            <span class="label">快递公司：</span>
            <span>{{ logisticsInfo.companyName }}</span>
          </div>
          <div class="tracking-info">
            <span class="label">快递单号：</span>
            <span>{{ logisticsInfo.trackingNumber }}</span>
            <el-button 
              type="text" 
              size="small" 
              @click="copyTrackingNumber(logisticsInfo.trackingNumber)"
              style="margin-left: 10px">
              复制单号
            </el-button>
          </div>
          <div class="status-info">
            <span class="label">物流状态：</span>
            <el-tag :type="getLogisticsStatusType(logisticsInfo.status)">
              {{ logisticsStatusMap[logisticsInfo.status] }}
            </el-tag>
          </div>
          <div class="time-info">
            <div>
              <span class="label">发货时间：</span>
              <span>{{ formatTime(logisticsInfo.createdAt) }}</span>
            </div>
            <div>
              <span class="label">更新时间：</span>
              <span>{{ formatTime(logisticsInfo.updatedAt) }}</span>
            </div>
            <div>
              <span class="label">预计到达：</span>
              <span>{{ formatTime(logisticsInfo.expectedArrivalTime) }}</span>
            </div>
          </div>
        </div>
        <div class="logistics-address">
          <h4>收货信息</h4>
          <div class="address-content">
            <p><span class="label">收货人：</span>{{ logisticsInfo.order.recvName }}</p>
            <p><span class="label">联系电话：</span>{{ logisticsInfo.order.recvPhone }}</p>
            <p><span class="label">收货地址：</span>{{ logisticsInfo.order.recvAddress }}</p>
          </div>
        </div>
      </div>
      <div v-else class="no-logistics">
        <el-empty description="暂无物流信息"></el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Request from '@/utils/request'
import Pagination from '@/components/Pagination/index.vue'
import { formatTime } from '@/utils/time'  // 导入时间格式化函数

export default {
  name: 'OrderManager',
  components: {
    Pagination
  },
  inject: ['userInfo'],
  data() {
    return {
      // 搜索表单
      searchForm: {
        id: undefined,
        status: undefined,
        userId: undefined,
        username: ''
      },
      // 查询参数
      queryParams: {
        currentPage: 1,
        size: 10
      },
      // 订单列表
      orders: [],
      // 订单退款状态缓存
      orderRefundStatus: {},
      // 总数
      total: 0,
      // 订单状态映射
      orderStatusMap: {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消',
        5: '已退款'
      },
      // 添加退款相关数据
      refundDialogVisible: false,
      currentOrder: null,
      refundInfo: null,
      orderRefund: null,
      refundForm: {
        status: 1,
        remark: ''
      },
      detailDialogVisible: false,
      refundStatusMap: {
        0: '申请中',
        1: '已同意',
        2: '已拒绝',
        3: '退款中',
        4: '已退款',
        5: '退款失败'
      },
      // 修改发货对话框
      shipDialogVisible: false,
      logisticsDialogVisible: false,
      shipForm: {
        orderId: null,
        receiverName: '',
        receiverPhone: '',
        receiverAddress: '',
        companyName: '',
        trackingNumber: '',
        expectedArrivalTime: '',
      },
      shipRules: {
        companyName: [
          { required: true, message: '请选择快递公司', trigger: 'change' }
        ],
        trackingNumber: [
          { required: true, message: '请输入快递单号', trigger: 'blur' }
        ],
        expectedArrivalTime: [
          { required: true, message: '请选择预计到达时间', trigger: 'change' }
        ],
      },
      logisticsInfo: null,
      logisticsStatusMap: {
        0: '待发货',
        1: '已发货',
        2: '已签收',
        3: '已取消',
        5: '已退款'
      },
      statistics: {}
    }
  },
  computed: {
    // 判断是否为管理员
    isAdmin() {
      return ['SUPER_ADMIN', 'ADMIN'].includes(this.userInfo.role)
    },
    // 判断是否为商户
    isMerchant() {
      return this.userInfo.role === 'MERCHANT'
    }
  },
  created() {
    this.getList()
    this.getStatistics()
  },
  methods: {
    // 获取订单列表
    async getList() {
      try {
        const params = {
          ...this.queryParams,
          ...this.searchForm
        }
        // 如果不是管理员，只能查看自己的订单
        if (!this.isAdmin) {
          params.merchantId = this.userInfo.id
        }
        const res = await Request.get('/order/page', { params })
        if (res.code === '0') {
          if (res.data.total === 0) {
            this.orders = []
            this.total = 0
          } else {
            this.orders = res.data.records
            this.total = res.data.total
            
            // 清空退款状态缓存
            this.orderRefundStatus = {}
            
            // 获取每个订单的退款状态
            for (const order of this.orders) {
              this.checkRefundRecord(order)
            }
          }
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
      }
    },
    // 获取订单统计数据
    async getStatistics() {
      try {
        const params = {}
        if (!this.isAdmin) {
          params.merchantId = this.userInfo.id
        }
        const res = await Request.get('/order/statistics', { params })
        if (res.code === '0') {
          this.statistics = res.data
          
          // 获取待处理退款数量
          if (this.isMerchant) {
            try {
              const refundRes = await Request.get('/refund/count/pending', { 
                params: { merchantId: this.userInfo.id } 
              })
              if (refundRes.code === '0') {
                this.$set(this.statistics, 'pendingRefundCount', refundRes.data || 0)
              }
            } catch (error) {
              console.error('获取待处理退款数量失败:', error)
              this.$set(this.statistics, 'pendingRefundCount', 0)
            }
          }
        }
      } catch (error) {
        console.error('获取订单统计数据失败:', error)
        this.$message.error('获取订单统计数据失败')
      }
    },
    // 搜索
    handleSearch() {
      this.queryParams.currentPage = 1
      this.getList()
      this.getStatistics() // 同时刷新统计数据
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        id: '',
        status: '',
        userId: '',
        username: ''
      }
      this.handleSearch()
      this.getStatistics()
    },
    // 获取订单状态类型
    getOrderStatusType(status) {
      const typeMap = {
        0: 'warning',   // 待支付
        1: 'primary',   // 已支付
        2: 'success',   // 已发货
        3: 'info',      // 已完成
        4: 'danger',    // 已取消
        5: 'info'       // 已退款
      }
      return typeMap[status] || 'info'
    },
    // 获取指定状态的订单数量
    getOrderCountByStatus(status) {
      return this.orders.filter(order => order.status === status).length
    },
    // 取消订单
    async handleCancel(order) {
      try {
        await this.$confirm('确认取消该订单?', '提示', {
          type: 'warning'
        })
        const res = await Request.put(`/order/${order.id}/status?status=4`)
        if (res.code === '0') {
          this.$message.success('订单已取消')
          this.getList()
        }
      } catch (error) {
        console.error('取消订单失败:', error)
      }
    },
    // 发货
    handleShip(order) {
      this.currentOrder = order
      this.shipForm = {
        orderId: order.id,
        receiverName: order.recvName,
        receiverPhone: order.recvPhone,
        receiverAddress: order.recvAddress,
        companyName: '',
        trackingNumber: '',
        expectedArrivalTime: '',
      }
      this.shipDialogVisible = true
    },
    // 确认收货
    async handleConfirm(order) {
      try {
        await this.$confirm('确认收到商品?', '提示', {
          type: 'warning'
        })
        const res = await Request.put(`/order/${order.id}/status?status=3`)
        if (res.code === '0') {
          this.$message.success('确认收货成功')
          this.getList()
        }
      } catch (error) {
        console.error('确认收货失败:', error)
      }
    },
    // 评价
    handleReview(order) {
      this.$router.push(`/review/${order.id}`)
    },
    // 查看详情
    async handleDetail(order) {
      this.currentOrder = order
      // 获取订单的退款信息
      try {
        const res = await Request.get(`/refund/order/${order.id}`)
        if (res.code === '0') {
          this.orderRefund = res.data
        } else {
          this.orderRefund = null
        }
      } catch (error) {
        console.error('获取退款信息失败:', error)
        this.orderRefund = null
      }
      this.detailDialogVisible = true
    },
    // 处理退款
    async handleRefund(order) {
      try {
        this.currentOrder = order
        // 获取退款信息
        const res = await Request.get(`/refund/order/${order.id}`)
        if (res.code === '0') {
          this.refundInfo = res.data
          // 检查退款状态，只有申请中的退款才能处理
          if (this.refundInfo.status === 0) {
            this.refundForm = {
              status: 1,
              remark: ''
            }
            this.refundDialogVisible = true
          } else {
            this.$message.info('该退款申请已处理，无法再次处理')
          }
        } else {
          this.$message.error(res.msg || '获取退款信息失败')
        }
      } catch (error) {
        console.error('获取退款信息失败:', error)
        this.$message.error('获取退款信息失败')
      }
    },
    // 提交退款处理
    async submitRefund() {
      try {
        if (!this.refundInfo) {
          this.$message.error('退款信息不存在')
          return
        }
        
        // 检查退款状态，只有申请中的退款才能处理
        if (this.refundInfo.status !== 0) {
          this.$message.warning('该退款申请已处理，无法再次处理')
          this.refundDialogVisible = false
          return
        }
        
        const res = await Request.put(`/refund/${this.refundInfo.id}/process`, null, {
          params: {
            status: this.refundForm.status,
            merchantRemark: this.refundForm.remark
          }
        })
        
        if (res.code === '0') {
          this.$message.success(this.refundForm.status === 1 ? '退款已通过' : '退款已拒绝')
          this.refundDialogVisible = false
          this.getList()
          this.getStatistics()
        } else {
          this.$message.error(res.msg || '退款处理失败')
        }
      } catch (error) {
        console.error('退款处理失败:', error)
        this.$message.error('退款处理失败')
      }
    },
    // 获取退款状态对应的类型
    getRefundStatusType(status) {
      const typeMap = {
        0: 'info',      // 申请中
        1: 'success',   // 已同意
        2: 'danger',    // 已拒绝
        3: 'warning',   // 退款中
        4: 'success',   // 已退款
        5: 'danger'     // 退款失败
      }
      return typeMap[status] || 'info'
    },
    // 添加格式化时间方法
    formatTime,
    // 添加删除订单方法
    async handleDelete(order) {
      try {
        await this.$confirm('确认删除该订单?', '提示', {
          type: 'warning'
        })
        const res = await Request.delete(`/order/${order.id}`)
        if (res.code === '0') {
          this.$message.success('订单已删除')
          this.getList()
        }
      } catch (error) {
        console.error('删除订单失败:', error)
      }
    },
    // 提交发货信息
    async submitShip() {
      try {
        await this.$refs.shipForm.validate()
        
        // 创建物流信息对象
        const logistics = {
          orderId: this.shipForm.orderId,
          receiverName: this.shipForm.receiverName,
          receiverPhone: this.shipForm.receiverPhone,
          receiverAddress: this.shipForm.receiverAddress,
          companyName: this.shipForm.companyName,
          trackingNumber: this.shipForm.trackingNumber,
          expectedArrivalTime: this.shipForm.expectedArrivalTime,
          status: 1  // 设置为已发货状态
        }
        
        // 调用发货接口
        const res = await Request.post(`/order/${this.shipForm.orderId}/ship`, logistics)
        
        if (res.code === '0') {
          this.$message.success('发货成功')
          this.shipDialogVisible = false
          this.shipForm = {  // 重置表单
            orderId: null,
            receiverName: '',
            receiverPhone: '',
            receiverAddress: '',
            companyName: '',
            trackingNumber: '',
            expectedArrivalTime: '',
          }
          this.getList()
        } else {
          this.$message.error(res.msg || '发货失败')
        }
      } catch (error) {
        console.error('发货失败:', error)
        this.$message.error('发货失败')
      }
    },
    // 添加查看物流信息方法
    async handleViewLogistics(order) {
      try {
        const res = await Request.get(`/logistics/order/${order.id}`)
        if (res.code === '0') {
          this.logisticsInfo = res.data
          // 添加物流时间显示
          this.logisticsInfo.createdTime = formatTime(res.data.createdAt)
          this.logisticsInfo.updatedTime = formatTime(res.data.updatedAt)
          this.logisticsDialogVisible = true
        }else{
          this.$message.error(res.msg || '暂无物流信息')
        }
      } catch (error) {
        console.error('获取物流信息失败:', error)
        this.$message.error('获取物流信息失败')
      }
    },
    // 获取物流状态对应的类型
    getLogisticsStatusType(status) {
      const typeMap = {
        0: 'warning',   // 待发货
        1: 'primary',   // 已发货
        2: 'success',   // 已签收
        3: 'danger',    // 已取消
        5: 'info'        // 已退款
      }
      return typeMap[status] || 'info'
    },
    // 复制快递单号
    copyTrackingNumber(trackingNumber) {
      const input = document.createElement('input')
      input.value = trackingNumber
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message.success('快递单号已复制')
    },
    // 解析凭证图片
    parseEvidenceImages(evidenceImages) {
      try {
        if (!evidenceImages) return [];
        const images = JSON.parse(evidenceImages);
        // 处理图片URL，确保正确显示
        return images.map(img => {
          // 如果已经是完整路径，直接返回
          if (img.startsWith('/api/')) {
            return img;
          }
          // 如果是相对路径，添加api前缀
          return `/api${img}`;
        });
      } catch (error) {
        console.error('解析凭证图片失败:', error);
        return [];
      }
    },
    // 检查订单是否有退款记录
    async checkRefundRecord(order) {
      try {
        const res = await Request.get(`/refund/order/${order.id}`)
        if (res.code === '0') {
          // 保存退款状态到缓存
          this.$set(this.orderRefundStatus, order.id, res.data)
          return true
        } 
        return false
      } catch (error) {
        console.error('检查退款记录失败:', error)
        return false
      }
    },
    // 添加行类名方法
    getRowClassName({row}) {
      // 如果订单有待处理的退款，添加高亮类名
      if (this.orderRefundStatus[row.id] && this.orderRefundStatus[row.id].status === 0) {
        return 'refund-pending-row';
      }
      return '';
    },
  }
}
</script>

  <style scoped>
.order-manager {
  padding: 24px;
  background-color: #fff8f0;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 500;
  color: #E67E22;
  margin: 0;
  margin-right: 15px;
}

.operation-area {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.statistics-cards {
  margin-bottom: 24px;
  position: relative;
}

.stat-card {
  border-radius: 12px;
  transition: all 0.3s;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.stat-card:hover {
  box-shadow: 0 6px 20px rgba(243, 156, 18, 0.1);
  transform: none;
}

.stat-content {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(to right, #fff, #fff8e6);
  position: relative;
  overflow: hidden;
}

.stat-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(to bottom, #F39C12, rgba(243, 156, 18, 0.5));
}

.stat-left {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: flex-start;
}

.stat-icon {
  font-size: 26px;
  color: #F39C12;
  opacity: 0.8;
  text-align: center;
  background-color: rgba(243, 156, 18, 0.1);
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #E67E22;
  margin-right: 16px;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 美化表格 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: none;
}

:deep(.el-table th) {
  background-color: #fff4e0;
  font-weight: 500;
  color: #E67E22;
  padding: 14px 0;
}

:deep(.el-table td) {
  padding: 14px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fffbf5;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 14px;
  color: #E67E22;
}

.product-price {
  font-size: 13px;
  color: #909399;
}

/* 美化对话框 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  padding: 24px;
  border-bottom: 1px solid #f5e8d3;
  margin: 0;
  background: #fff4e0;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 500;
  color: #E67E22;
}

:deep(.el-dialog__body) {
  padding: 32px 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f5e8d3;
  background: #faf7f0;
}

/* 美化表单 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #E67E22;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #f0d5b3;
  transition: all 0.3s;
  padding: 0 15px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-input__inner:focus) {
  border-color: #F39C12;
  box-shadow: 0 0 0 2px rgba(243, 156, 18, 0.2);
}

:deep(.el-select .el-input__inner:focus) {
  border-color: #F39C12;
}

:deep(.el-button--primary) {
  background-color: #F39C12;
  border-color: #F39C12;
  color: #fff;
}

:deep(.el-button--primary:hover) {
  background-color: #E67E22;
  border-color: #E67E22;
  color: #fff;
}

:deep(.el-button--text) {
  color: #F39C12;
}

.delete-btn {
  color: #f56c6c;
  margin-left: 12px;
}

.delete-btn:hover {
  color: #ff4949;
}

:deep(.el-switch.is-checked .el-switch__core) {
  border-color: #F39C12;
  background-color: #F39C12;
}

.refund-info {
  padding: 20px;
  background: #fff4e0;
  border-radius: 8px;
  margin-bottom: 20px;
}

.refund-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5e8d3;
  margin-bottom: 20px;
}

.refund-status {
  font-size: 16px;
}

.refund-no {
  color: #606266;
  font-size: 14px;
}

.evidence-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.value.highlight {
  color: #f56c6c;
  font-weight: 600;
}

.refund-operation {
  padding: 0 20px;
}

.order-detail {
  padding: 20px;
}

.detail-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5e8d3;
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.detail-section h4 {
  font-size: 16px;
  color: #E67E22;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.4;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  width: 100px;
  color: #909399;
}

.product-detail-info {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #fff4e0;
  border-radius: 8px;
}

.product-info-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  font-size: 14px;
  color: #E67E22;
  font-weight: 500;
}

.product-price {
  color: #606266;
  font-size: 13px;
  display: flex;
  gap: 16px;
}

.total-price {
  color: #f56c6c;
  font-size: 14px;
  font-weight: 500;
}

/* 添加物流信息相关样式 */
.logistics-info {
  padding: 20px;
}

.logistics-header {
  background: #fff4e0;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.logistics-header > div {
  margin-bottom: 12px;
}

.logistics-header > div:last-child {
  margin-bottom: 0;
}

.logistics-header .label {
  color: #909399;
  margin-right: 8px;
}

.time-info {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #f0d5b3;
}

.time-info > div {
  margin-bottom: 8px;
}

.logistics-address {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.logistics-address h4 {
  font-size: 16px;
  color: #E67E22;
  margin: 0 0 16px 0;
}

.address-content p {
  margin: 8px 0;
  color: #606266;
}

/* 添加凭证图片样式 */
.evidence-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #f0d5b3;
}

.evidence-section h5 {
  font-size: 14px;
  color: #606266;
  margin: 0 0 12px 0;
  font-weight: 500;
}

.detail-item .value.highlight {
  color: #f56c6c;
  font-weight: 600;
}

/* 分页样式 */
:deep(.el-pagination) {
  padding: 20px 0;
  text-align: right;
}

:deep(.el-pagination button) {
  background: none;
}

:deep(.el-pagination .btn-next),
:deep(.el-pagination .btn-prev) {
  border: 1px solid #f0d5b3;
  border-radius: 8px;
}

:deep(.el-pager li) {
  border-radius: 8px;
  margin: 0 3px;
}

:deep(.el-pager li.active) {
  background-color: #F39C12;
  color: #fff;
}

:deep(.el-tag--info) {
  background-color: rgba(243, 156, 18, 0.1);
  border-color: rgba(243, 156, 18, 0.2);
  color: #F39C12;
}

:deep(.el-button) {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button:hover) {
  transform: none;
  box-shadow: none;
}

/* 添加用户信息列样式 */
.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-size: 14px;
  color: #E67E22;
  font-weight: 500;
}

.user-username {
  font-size: 12px;
  color: #909399;
}

.text-muted {
  color: #909399;
}

.status-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.refund-badge {
  position: relative;
  background-color: #fff0f0;
  color: #f56c6c;
  font-size: 12px;
  padding: 2px 6px;
  border: 1px solid #f56c6c;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.4);
  }
  70% {
    box-shadow: 0 0 0 5px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

.refund-action-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: white;
  font-weight: bold;
  position: relative;
  overflow: hidden;
}

.refund-action-btn::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: rgba(255, 255, 255, 0.2);
  transform: rotate(45deg);
  animation: shine 2s infinite;
}

@keyframes shine {
  0% {
    transform: translateX(-100%) rotate(45deg);
  }
  100% {
    transform: translateX(100%) rotate(45deg);
  }
}

.refund-stat-card {
  border: 1px solid rgba(245, 108, 108, 0.2);
}

.refund-stat-card:hover {
  box-shadow: 0 6px 20px rgba(245, 108, 108, 0.1);
}

.refund-stat-card .stat-content::before {
  background: linear-gradient(to bottom, #f56c6c, rgba(245, 108, 108, 0.5));
}

.refund-icon {
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
}

.refund-value {
  color: #f56c6c;
}

/* 待处理退款行样式 */
:deep(.refund-pending-row) {
  background-color: #fff8f8 !important;
}

:deep(.refund-pending-row:hover > td) {
  background-color: #ffeaea !important;
}

:deep(.refund-pending-row td) {
  border-bottom: 1px solid rgba(245, 108, 108, 0.2) !important;
}
</style> 